package com.wnxy.sddfp.common.util;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.Map;

public class JwtTemplate {

    // 密钥对文件
    private String path = "jwt.jks";
    // 密钥对前缀
    private String alias = "jwt";
    // 密钥对访问密码
    private String keySecurity = "123456";

    /**
     * 创建密钥对
     */
    private KeyPair createKeyPair(){
        // 创建工厂
        KeyStoreKeyFactory factory = new KeyStoreKeyFactory(
                new ClassPathResource(path),keySecurity.toCharArray());
        // 创建密钥对对象
        KeyPair keyPair = factory.getKeyPair(alias);
        return keyPair;
    }

    /**
     * 创建签名器
     */
    private JWTSigner createJwtSigner(){
        // 创建签名器对象
        JWTSigner jwtSigner = JWTSignerUtil.createSigner("RSA",createKeyPair());
        return jwtSigner;
    }

    /**
     * 创建token
     */
    public String createToken(Map<String,Object> payload) {
        return JWTUtil.createToken(payload, createJwtSigner());
    }

    /**
     * 验证token
     */
    public boolean verify(String token){
        return JWTUtil.verify(token, createJwtSigner());
    }

    /**
     * 解析token
     */
    public Object parseToken(String token,String key) {
        JWT jwt = JWTUtil.parseToken(token);
        Object result = jwt.getPayload(key);
        return result;
    }
}
